"""
2.	机器人是模仿人类和动物行为的机器，其内部有台计算机，通过读取各个传感器的信息，做出判断，并且调用电机实现相关的动作，完成指令。
给定“手势识别”数据集，有三个指令：左转、右转、停止。利用深度学习平台预训练模型mobilenet，搭建后端网络，进行模型训练和测试，按下面的要求，
完成相应代码（25分）
"""
import os
import sys
import cv2 as cv
import numpy as np
from python_ai.common.xcommon import *
from python_ai.common.read_data.redis_numpy import toRedisNd
from python_ai.cate.redis.vm_ubun20_redis import r
import datetime

SIDE = 224
ALPHA = 1e-3
BATCH_SIZE = 32
N_EPOCH = 2
BASE_DIR, FILE_NAME = os.path.split(__file__)
# dir = 'data/gesture'
dir = '../../../../../large_data/CV4/_many_files/Gesture_Recognition'

IMG_DIR = os.path.join(BASE_DIR, dir)

# ①	导入“手势识别”数据集
x, y, path = [], [], []
labels_arr = []
yi = 0
cnt = 0
print('Loading ...')
dt1 = datetime.datetime.now()
for sub_dir_name in os.listdir(IMG_DIR):
    sub_dir_path = os.path.join(IMG_DIR, sub_dir_name)
    if not os.path.isdir(sub_dir_path):
        continue
    print(f'Loading {sub_dir_name} ...')
    labels_arr.append(sub_dir_name)
    for file_name in os.listdir(sub_dir_path):
        if '.nomedia' == file_name:
            continue
        file_path = os.path.join(sub_dir_path, file_name)
        img = cv.imread(file_path, cv.IMREAD_COLOR)
        img = cv.resize(img, (SIDE, SIDE))
        img = np.float32(img) / 255.
        x.append(img)
        y.append(yi)
        path.append(file_path)
        cnt += 1
        if cnt % 25 == 0:
            print(f'Loaded {cnt} pictures.')
    yi += 1
x = np.float32(x)
y = np.int64(y)
path = np.array(path)
labels_arr = np.array(labels_arr)
dt2 = datetime.datetime.now()
print(f'Loaded. Time usage: {dt2 - dt1}')
print('x', x.shape)
print('y', y.shape)
print('path', np.shape(path))

print('Putting into redis ...')
r_key = ensure_filename(BASE_DIR, True) + 'v1'
print('redis key', r_key)
dt1 = datetime.datetime.now()
toRedisNd(r, x, f'{r_key}_x')
toRedisNd(r, y, f'{r_key}_y')
toRedisNd(r, path, f'{r_key}_path')
toRedisNd(r, labels_arr, f'{r_key}_labels_arr')
dt2 = datetime.datetime.now()
print(f'Put into redis. Time usage: {dt2 - dt1}')
